package com.moco.launcher.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.moco.launcher.R;
import com.moco.launcher.UpdateReceiver;
import com.moco.launcher.bean.AboutItemBean;
import com.moco.launcher.play.AndroidMusicPlayer;
import com.oazon.common.Logger;
import com.oazon.common.Settings;
import com.oazon.common.util.LogsReaderWriter;
import com.oazon.moco.link.bean.BatteryInfo;
import com.oazon.moco.link.bean.Mcu;
import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.serialport.SerialHandlerService;
import com.oazon.moco.serialport.SerialSend;
import com.oazon.moco.serialport.core.Serial;
import com.oazon.system.SysActionChannal;
import com.oazon.system.broadcast.BootBroadcastReceiver;
import com.oazon.voicelib.service.SpeechManage;

public class AboutActivity extends BaseActivity implements OnClickListener {
	private ImageView about_exit;
	private ListView messages;
    private String TAG = "AboutActivity";
	private List<AboutItemBean> items;
	
	//-------for--alarmClock--for---takeVideo------------------------------------------
	
	private int countIpClick=0;
	private long lastClickTime=0;
	private long  firstClickTime;
	//--------------------------------------------------------

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.about_activity);

		messages = (ListView) findViewById(R.id.messages);
        messages.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if(position==0){
					countIpClick++;
					if(countIpClick==1){
						 firstClickTime = System.currentTimeMillis();
					}
					Log.e(TAG, "countIpClick"+countIpClick);
					if(countIpClick==4){
						lastClickTime =System.currentTimeMillis();
						if(lastClickTime-firstClickTime<1000){
							Intent intent = new Intent(AboutActivity.this,AlarmClockActivity.class);
							startActivity(intent);
							firstClickTime=0;
							lastClickTime=0;
						}

						countIpClick=0;
					}
				}
			}
		});
		items = new ArrayList<AboutItemBean>();

		about_exit = (ImageView) findViewById(R.id.about_exit);
		about_exit.setOnClickListener(this);


	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}

	@Override
	public void onClick(View v) {
		finish();
	}
	
	@Override
	protected void onResume() {
		init();
		super.onResume();
	}

	
	private void init(){
		
		SerialSend.getInstance().sendStatus(SerialSend.Serial_GET_BATTERY_VOLTAGE);
		SerialSend.getInstance().sendStatus(SerialSend.Serial_POWER_PERCENT);

		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = intToIp(ipAddress);
		items.clear();
		Log.i(TAG, "items.size=="+items.size());
		AboutItemBean ipBean = new AboutItemBean();
		ipBean.setTitle("IP地址");
		ipBean.setContent(ip);
		items.add(ipBean);

		String systemVersion = getDragonVersion();
		String softVersion = getAppVersionName(AboutActivity.this);

		items.add(new AboutItemBean("版本", systemVersion + "-" + softVersion));

		items.add(new AboutItemBean("电池电量",
				BatteryInfo.ChargePercent + "%"));
		items.add(new AboutItemBean("电压",
				BatteryInfo.voltage+""));

		if (BatteryInfo.isDC) {
			items.add(new AboutItemBean("外部电源", "已插入"));
		} else {
			items.add(new AboutItemBean("外部电源", "未插入"));
		}

		if (BatteryInfo.IsCharging) {
			if (BatteryInfo.ChargePercent == 100) {
				items.add(new AboutItemBean("充电状态", "已充满"));
			} else {
				items.add(new AboutItemBean("充电状态", "正在充电"));
			}
		} else {
			items.add(new AboutItemBean("充电状态", "未充电"));
		}

		if (Mcu.mcu_verison != null) {
			String mucVersion = null;
			mucVersion = StringUtils.replace(Mcu.mcu_verison.trim(), " ", "-");
			items.add(new AboutItemBean("固件版本号", mucVersion));
		}else{
			items.add(new AboutItemBean("固件版本号", ""));
		}
		items.add(new AboutItemBean("设备序列号", LinkSDK.UUID));
		
		
		String serviceName = Settings.getInstance(this).get("nsd.serv.name");
		if(serviceName != null &&!"".equals(serviceName)){
			items.add(new AboutItemBean("服务名称", serviceName));
		}else{
			items.add(new AboutItemBean("服务名称", "O2Player"));
		}

		items.add(new AboutItemBean("工作时间", getWorkTime()));

		MessagesAdapter adapter = new MessagesAdapter();

		messages.setAdapter(adapter);
	}

	public String getWorkTime() {
		String returnTime = "";
		long bootTime = Settings.getInstance(this.getApplicationContext()).getLong("boot_time", 0);
		Log.d("wowdd1", "getWorkTime " + bootTime);
		if (bootTime != 0) {
			long diff = System.currentTimeMillis() - bootTime;
			//1H =60m=3600s   X / 3600 ==>H
			//1m =60s        (X - H) / 60 ==>m

			long hour = ((diff / 1000) / 3600);
			long min = (diff - (hour * 3600 * 1000)) / (60 * 1000);

			if (hour > 1000) {
				hour = 0;
				min = 0;
				Settings.getInstance(this.getApplicationContext()).setLong("boot_time", System.currentTimeMillis());
			}

			if (hour > 0) {
				returnTime = returnTime + hour + "小时";
			}

			if(min > 0) {
				returnTime = returnTime + min + "分";
			}

			if (hour <= 0 && min <= 0) {
				returnTime = "0分";
			}
		}
		return returnTime;
	}

	// 获取当前版本号
	private String getAppVersionName(Context context) {
		String versionName = "";
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(
					"com.moco.launcher", 0);
			versionName = packageInfo.versionName;
			if (TextUtils.isEmpty(versionName)) {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionName;
	}

	public String getDragonVersion() {
		try {
			String str1 = "/system/build.prop";
			return LogsReaderWriter.readFromFile(str1, "ro.product.firmware")
					.substring(20);

		} catch (Exception e) {
			return "";
		}
	}

	/*
	 * BatteryEventListener batteryEventListener = new
	 * BatteryEventListener(LinkEventController.uiSource){
	 * 
	 * protected void setBatteryPercent(int charge_percent) {
	 * 
	 * power.setText("系统电量:" + charge_percent + "%"); };
	 * 
	 * protected void setBatteryState(BatteryStatus state) {
	 * 
	 * if(state.equals(BatteryStatus.CHARGE_OFF)){ isChangreTxt.setText("充电状态:"
	 * + "电源未接入"); }else if(state.equals(BatteryStatus.CHARGE_PERCNET)){
	 * isChangreTxt.setText("充电状态:" + "正在充电"); }else
	 * if(state.equals(BatteryStatus.FULL_YES)){ isChangreTxt.setText("充电状态:" +
	 * "充电完成"); } }; };
	 */

	class ViewHodler {
		TextView title;
		TextView content;
	}

	private static int click_count_log = 0;
	private static int click_count_factory = 0;

	class MessagesAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MessagesAdapter() {
			mInflater = LayoutInflater.from(AboutActivity.this);
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHodler hodler = null;
			if(convertView == null){
				hodler = new ViewHodler();
				convertView = mInflater.inflate(R.layout.about_item, null);
			
				hodler.title = (TextView) convertView.findViewById(R.id.title);
				hodler.content = (TextView) convertView.findViewById(R.id.content);
				
				convertView.setTag(hodler);


			}else{
				hodler = (ViewHodler) convertView.getTag();
			}
			
			hodler.title.setText(items.get(position).getTitle());
			hodler.content.setText(items.get(position).getContent());

			forDebug(items.get(position).getTitle(), hodler.title);


			
			return convertView;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

	}

	private void forDebug(String title, TextView view) {
		if("工作时间".equals(title)) {
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {

					click_count_factory++;
					if (click_count_factory == 5) {
						click_count_factory = 0;
						startFactory(); 
					}
				}
			});
		} else if("设备序列号".equals(title)) {
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					click_count_log++;
					if (click_count_log == 10) {
						click_count_log = 0;
						if (!Settings.getInstance(AboutActivity.this).getBoolean(Logger.O2_DEBUG, false)) {
							Settings.getInstance(AboutActivity.this).setBoolean(Logger.O2_DEBUG, true);
							Logger.enableDebug();
						} else {
							Settings.getInstance(AboutActivity.this).setBoolean(Logger.O2_DEBUG, false);
							Logger.disableDebug();
						}
					}
				}
			});
		}
	}

	private void startFactory() {
		SerialSend.getInstance().sendStatus(SerialSend.Serial_WATCHDOG_CLOSE);
        SysActionChannal.getInstance().setPauseAllTimer(true);
        SpeechManage.getInstance().stopWake();
		AndroidMusicPlayer.getInstance().stop();
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				SerialSend.getInstance().close();
				Serial.getInstance().stop();

				ComponentName componetName = new ComponentName(
						"com.example.dragontest",
						"com.example.dragontest.MainActivity");
				Intent intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setComponent(componetName);
				startActivity(intent);
			}

		}, 2000);

	}


}
